<?php
class User extends Model_Abstract
{
	public function register($email, $password, $firstname, $lastname, $gender, $birthday, $phone,  $siteid, $credit, $oauth_provider = '', $oauth_uid = '', $optin_edu='0', $optin_sj='0', $optin_inpays='0')
	{
		$now = time();
		$token = Util::generateToken();
		try
		{
			if (isset($_SESSION['PLAYED']))
			{
				$sql = "insert into users set email=?, firstname=?, lastname=?, gender=?, birthday=?, phone=?,  password=?, created=?, token=?, site_id=?, balance=1, won=1, daily=1, weekly=1, monthly=1, played=1, daily_played=1, weekly_played=1, monthly_played=1, credit=?, last_visit=?, oauth_provider=?, oauth_uid=?, optin_edu=?, optin_sj=?, optin_inpays=?, ip=? ";
			}
			else
			{
				$sql = "insert into users set email=?, firstname=?, lastname=?, gender=?, birthday=?, phone=?,  password=?, created=?, token=?, site_id=?, credit=1+?, last_visit=?, oauth_provider=?, oauth_uid=?, optin_edu=?, optin_sj=?, optin_inpays=?, ip=? ";
			}
			$result = $this->_connection->execute($sql, array($email, $firstname, $lastname, $gender, $birthday, $phone, Util::encodePassword($password), $now, $token, $siteid, $credit, $now, $oauth_provider, $oauth_uid, $optin_edu, $optin_sj, $optin_inpays, ip2long(Util::getClientIp())));
			if($result)
				return $token;
		}
		catch (Exception $e)
		{
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function refitIp($uid)
	{
		try
		{
			$sql = " UPDATE users SET ip=? WHERE id=? ";
			return $this->_connection->execute($sql, array(ip2long(Util::getClientIp()), $uid));
		}
		catch (Exception $e)
		{
			QLog::log(__CLASS__. ' ' . __METHOD__ . '---' . $e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function getFbuser($fb_uid)
	{
		try{
			$sql = "SELECT * FROM users WHERE oauth_provider=? AND 	oauth_uid=? ";
			$result = $this->_connection->query($sql, array('Facebook', $fb_uid));
			if(count($result) == 0){
				return false;
			}else{
				return $result[0];
			}
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
		
	public function exist($email, $siteid)
	{
		try{
			$sql = 'select id, firstname, lastname from users where email = ? and site_id=? limit 1';
			$result = $this->_connection->query($sql, array($email, $siteid));
			if($result){
				return $result[0];
			}
			return false;
		}
		catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function updateProfile($id, $email, $firstname, $lastname, $address1, $address2, $city, $state
							, $zipcode, $phone, $gender, $birthday, $optin_edu, $optin_sj, $optin_inpays, $optin_greateamerican, $unsub =0){
		try{
			$sql = "update users set email=?, firstname=?, lastname=?, address1=?, address2=?, city=?
						, state=?, zipcode=?, phone=?, gender=?, birthday=?, optin_edu=?, optin_sj=?, optin_inpays=?, optin_greateamerican=?, unsub=? where id=?";
			$result = $this->_connection->execute($sql, array($email, $firstname, $lastname
						, $address1, $address2, $city, $state, $zipcode, $phone, $gender, $birthday, $optin_edu, $optin_sj, $optin_inpays, $optin_greateamerican, $unsub, $id));
			return $result;
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function updatePassword($uid, $password){
		try{
			$sql = "update users set password=? where id=?";
			$result = $this->_connection->execute($sql, array(Util::encodePassword($password), $uid));
			return $result;
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function getProfileInfo($id){
		try{
			$sql = "select id, email, firstname, lastname, address1, address2, city
						, state, zipcode, phone, gender, birthday, optin_edu, optin_sj, optin_inpays, optin_greateamerican, unsub from users where id=? limit 1";
			$result = $this->_connection->query($sql, array($id));
			if(count($result) == 0){
				return false;
			}else{
				return $result[0];
			}
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function getLoginInfo($id){
		try{
			$sql = "select firstname, lastname, credit, balance, won, monthly, weekly, daily,
							daily_played, weekly_played, monthly_played, played from users where id=? limit 1";
			$result = $this->_connection->query($sql, array($id));
			if(count($result) == 0){
				return false;
			}else{
				return $result[0];
			}
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	//TODO: clear unneccessary info
	public function getUserById($id)
	{
		try{
			$sql = 'select * from users where id=? limit 1';
			$result = $this->_connection->query($sql, array($id));
			if (count($result) == 0){
				return false;
			}else{
				return $result[0];
			}
		}
		catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}

	public function getUserByEmail($email, $siteid)
	{
		try{
			$sql = 'select * from users where email=? and site_id=? limit 1';
			$result = $this->_connection->query($sql, array($email, $siteid));
			if (count($result) == 0){
				return false;
			}else{
				return $result[0];
			}
		}
		catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}

	public function valid($email, $password, $siteid){
		try{
			$sql = 'select id, firstname, lastname, email, address1, credit, balance, created, last_visit, ip  from users where email=? and password=? and site_id=? and unsub=0 limit 1';
			$result = $this->_connection->query($sql, array($email, Util::encodePassword($password), $siteid));
			if (count($result) == 0){
				return false;
			}else{
				return $result[0];
			}
		}
		catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function updateLastVisit($id){
		try{
			$sql = 'update users set last_visit=? where id=?';
			$result = $this->_connection->execute($sql, array(time(), $id));
			return $result;
		}
		catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function resetPassword($id, $password){
		try{
			$sql = 'update users set password=? where id=?';
			$result = $this->_connection->execute($sql, array(Util::encodePassword($password), $id));
			return $result;
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function forgetPassword($email, $site_id){
		$sql = 'update users set password=? where email=? and site_id=? and unsub=0';
		$password = Util::getRandonPassword();
		try{
			$result =  $this->_connection->execute($sql, array($password[1], $email, $site_id));
			if($result)
				return $password[0];
			return false;
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function changeSubscribe($id, $sub=1){
		try{
			$sql = 'update users set unsub=? where id=?';
			$result = $this->_connection->execute($sql, array($sub, $id));
			return $result;
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	/*
	public function valdiateUser($email, $password, $siteid){
		try{
			$sql = 'select id, balance, email, firstname, lastname, address1, balance, credit, won, monthly, weekly, daily, daily_played, weekly_played, monthly_played, played, last_visit, created from users where email=? and site_id=? and password=? and unsub=1';
			$result = $this->_connection->query($sql, array($email, $siteid, Util::encodePassword($password)));
			if(count($result) == 0){
				return false;
			}else{
				return $result[0];
			}
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	*/
	public function getHistory($uid){
		try{
			$sql = 'select monthly, daily, weekly, daily_played,  weekly_played, monthly_played from users where id=?';
			$result = $this->_connection->query($sql, array($uid));
			if(count($result) == 0){
				return false;
			}else{
				return $result[0];
			}
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function offerUserCredits($credit, $uid){
		try{
			$sql = 'update users set credit=credit+? where id=?';
			$result = $this->_connection->execute($sql, array($credit, $uid));
			return $result;
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function offerUserPartialCredits($credit, $uid){
		try{
			$sql = 'update users set credit=credit+floor((partial+?)/100), partial=(partial+?)%100 where id=?';
			$result = $this->_connection->execute($sql, array($credit, $credit, $uid));
			return $result;
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function offerUserCreditsByMonetizations($uid, $credits){
		try{
			$sql = 'update users set credit=credit+? where id=?';
			$result = $this->_connection->execute($sql, array($credits, $uid));
			return $result;
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
/*	public function initGameParams($uid){
		try{
			$sql = 'select u.id, u.credit, u.won, s.jackpot from users as u left join sites as s on u.site_id = s.id where u.id=? limit 1';
			$result = $this->_connection->query($sql, array($uid));
			if(count($result) == 0){
				return false;
			}else{
				return $result[0];
			}
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
*/
	public function afterWheelPlay($uid, $won, $credit=0)
	{
		try
		{
			$sql = 'update users set credit=credit-1+?, won=won+?, balance=balance+?, daily=daily+?, weekly=weekly+?, monthly=monthly+?, played=played+1, daily_played=daily_played+1, weekly_played=weekly_played+1, monthly_played=monthly_played+1 where id=?';
			$result = $this->_connection->execute($sql, array($credit, $won, $won, $won, $won, $won, $uid));
			return $result;
		}
		catch (Exception $e)
		{
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	public function afterSlotPlay($uid, $bet, $won, $credit=0)
	{
		try
		{
			$sql = 'update users set credit=credit-?+?, won=won+?, balance=balance+?, daily=daily+?, weekly=weekly+?, monthly=monthly+?, played=played+?, daily_played=daily_played+?, weekly_played=weekly_played+?, monthly_played=monthly_played+? where id=?';
			$result = $this->_connection->execute($sql, array($bet, $credit, $won, $won, $won, $won, $won, $bet, $bet, $bet, $bet, $uid));
			return $result;
		}
		catch (Exception $e)
		{
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function beforePokerPlay($uid, $bet)
	{
		try
		{
			$sql = 'update users set credit=credit-?, played=played+?, daily_played=daily_played+?, weekly_played=weekly_played+?, monthly_played=monthly_played + ? where id=?';
			$result = $this->_connection->execute($sql, array($bet, $bet, $bet, $bet, $bet, $uid));
			return $result;
		}
		catch (Exception $e)
		{
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}

	public function afterPokerPlay($uid, $won)
	{
		try
		{
			$sql = 'update users set won=won+?, balance=balance+?, daily=daily+?, weekly=weekly+?, monthly=monthly+? where id=?';
			$result = $this->_connection->execute($sql, array($won, $won, $won, $won, $won, $uid));
			return $result;
		}
		catch (Exception $e)
		{
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	public function drawMoney($amount, $uid){
		try
		{
			if($this->canDraw($amount, $uid)){
				$this->_connection->beginTransactionW();
				$sql = 'update users set balance=balance-? where id=?';
				$result = $this->_connection->execute($sql, array($amount, $uid));
				if($result){
					$fulmodel = new Fulfillment();
					$result = $fulmodel->add($uid, $amount, $status='Pending');
					if($result){
						$this->_connection->commitW();
						return true;
					}else{
						$this->_connection->rollBackW();
						return false;
					}
				}
			}
		}
		catch (Exception $e)
		{
			$this->_connection->rollBackW();
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	private function canDraw($amount, $uid){
		try
		{
			$sql = 'select balance from users where id=?';
			$result = $this->_connection->query($sql, array($uid));
			if($result && $amount<=$result[0]['balance'])
				return true;
			return false;
		}
		catch (Exception $e)
		{
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}

	public function getOffersByUserId($uid)
	{
		try
		{
			$sql = 'select count(*) as count from rewards where user_id=?';
			$result = $this->_connection->query($sql, array($uid));
			return $result[0]['count'];
		}
		catch (Exception $e)
		{
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function validateCookie($email, $cookie, $site_id){
		try
		{
			$sql = 'select id, firstname, lastname, email, address1, credit, balance, created, last_visit, confirmed from users where email=? and cookie=? and site_id=?';
			$result = $this->_connection->query($sql, array($email , $cookie, $site_id));
			if(!empty($result))
				return $result[0];
			return false;
		}
		catch (Exception $e)
		{
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function updateCookie($uid, $cookie){
		try
		{
			$sql = 'update users set cookie=? where id=?';
			$result = $this->_connection->execute($sql, array($cookie, $uid));
			return $result;
		}
		catch (Exception $e)
		{
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}

	public function recordCampaign($uid, $campaign)
	{
		try
		{
			$sql = 'update users set cam=?, pub=?, pla=?, cus=?, cre=? where id=?';
			$result = $this->_connection->execute($sql, array($campaign['cam'], $campaign['pub'], $campaign['pla'], $campaign['cus'], $campaign['cre'], $uid));
			return $result;
		}
		catch (Exception $e)
		{
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function confirmAccount($id){
		try
		{
			$sql = 'update users set confirmed=1 where id=?';
			$result = $this->_connection->execute($sql, array($id));
			return $result;
		}
		catch (Exception $e)
		{
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}

	public function confirm($token , $name)
	{
		try
		{
			$sql = 'select * from users where token=? and confirmed=0';
			$result = $this->_connection->query($sql, array($token));
			if (count($result) < 1)
			{
				return false;
			}
			else if (md5($result[0]['firstname']) == $name)
			{
				return $result[0];
			}
			else
			{
				return false;
			}
		}
		catch (Exception $e)
		{
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}

	public function clearToken($id)
	{
		try
		{
			$sql = 'update users set token="" where id=?';
			$result = $this->_connection->execute($sql, array($id));
			return $result;
		}
		catch (Exception $e)
		{
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}

	public function getTodayWon($site_id)
	{
		try
		{
			$sql = 'select sum(daily) as today from users where site_id=?';
			$result = $this->_connection->query($sql, array($site_id));
			return $result[0]['today'];
		}
		catch (Exception $e)
		{
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function getRecordingInfo($uid)
	{
		try
		{
			$sql = 'select u.cam, u.pub, u.pla, u.cus, u.cre, u.lu, u.buy_type, u.media_type, u.offer, s.domain, s.game  from users u left join sites s on u.site_id = s.id where u.id=?';
			$result = $this->_connection->query($sql, array($uid));
			if (count($result) == 0)
			{
				return false;
			}
			else
			{
				return $result[0];	
			}
		}
		catch (Exception $e)
		{
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function rewardReference($uid, $credit, $name)
	{
		try
		{	
			$sql = 'UPDATE `users` SET credit=credit+? WHERE id=? ';
			$result = $this->_connection->execute($sql, array($credit, $uid), true);
			
			$sql = 'INSERT INTO `rewards` SET `user_id`=?, `name`=?, `credit`=?, `created`=? ';
			$result = $this->_connection->execute($sql, array($uid, $name, $credit, time()), true);
			return $result;
		}
		catch (Exception $e)
		{
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}		
	}
	
	public function getUnsubByEmail($email)
	{
		try
		{
			$sql = " SELECT unsub FROM users WHERE email=? ";
			$result = $this->_connection->query($sql, array($email));
			if(count($result) > 0){
				return $result[0]['unsub'];
			}else{
				return false;
			}
		}
		catch (Exception $e)
		{
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	public function setFired($uid){
		try
		{
			$sql = 'update users set fired=1 where id=?';
			$result = $this->_connection->execute($sql, array($uid));
			return $result;
		}
		catch (Exception $e)
		{
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	
}